import 'package:flutter/material.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:mi_mang_flutter/api/user_api.dart';
import 'package:mi_mang_flutter/config/configs.dart';
import 'package:mi_mang_flutter/generated/icon/Iconfont.dart';
import 'package:mi_mang_flutter/provider/app_theme.dart';
import 'package:mi_mang_flutter/res/dimens.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/keyboard_action_util.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'login_router.dart';

class RegisterPage extends StatefulWidget {
  RegisterPage({Key? key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage>
    with SingleTickerProviderStateMixin {
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  final FocusNode _usernameNodeText = FocusNode();
  final FocusNode _passwordNodeText = FocusNode();

  // 是否同意条款
  bool _isAgree = false;

  bool _isClick = false;

  @override
  void initState() {
    super.initState();

    //监听输入改变
    _usernameNodeText.addListener(_verify);
    _passwordController.addListener(_verify);
  }

  /// 监听按钮是否可点击
  void _verify() {
    String username = _usernameController.text;
    String password = _passwordController.text;
    if (username.isEmpty) {
      setState(() {
        _isClick = false;
      });
      return;
    }
    if (password.isEmpty) {
      setState(() {
        _isClick = false;
      });
      return;
    }
    setState(() {
      _isClick = true;
    });
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        foregroundColor: !ThemeUtil.isDark(context) ? Colors.black : null,
        backgroundColor: Colors.transparent,
        actions: <Widget>[
          TextButton(
            child: Text(
              i18n(context).existingAccount,
            ),
            onPressed: () {
              NavigatorUtils.goBack(context);
            },
          ),
        ],
      ),
      body: KeyboardActions(
        // tapOutsideToDismiss: true,
        config: getKeyboardActionsConfig(context, [
          _usernameNodeText,
          _passwordNodeText,
        ]),
        child: Padding(
          padding: EdgeInsets.symmetric(
            horizontal: Dimens.gapDp30,
            vertical: Dimens.gapDp10,
          ),
          child: _buildLogin(),
        ),
      ),
      backgroundColor: Theme.of(context).colorScheme.surface,
    );
  }

  /// 登录部分布局
  Widget _buildLogin() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          i18n(context).registerAccount,
          style: TextStyle(
            fontSize: Dimens.fontSp32,
            fontWeight: FontWeight.w500,
          ),
        ),
        Gaps.vGap5,
        TextField(
          decoration: InputDecoration(
            suffixIcon: Icon(Icons.person),
            border: UnderlineInputBorder(
              borderSide: BorderSide(width: 0.6),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(width: 0.6),
            ),
            hintText: i18n(context).account,
            contentPadding: EdgeInsets.symmetric(vertical: Dimens.gapDp22),
          ),
          focusNode: _usernameNodeText,
          controller: _usernameController,
          textInputAction: TextInputAction.done,
          keyboardType: TextInputType.text,
        ),
        TextField(
          decoration: InputDecoration(
            suffixIcon: Icon(Icons.lock),
            border: UnderlineInputBorder(
              borderSide: BorderSide(width: 0.5),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(width: 0.5),
            ),
            hintText: i18n(context).password,
            contentPadding: EdgeInsets.symmetric(vertical: Dimens.gapDp22),
          ),
          focusNode: _passwordNodeText,
          controller: _passwordController,
          textInputAction: TextInputAction.done,
          keyboardType: TextInputType.visiblePassword,
          obscureText: true,
        ),
        Gaps.vGap35,
        ElevatedButton(
          child: Container(
            alignment: Alignment.center,
            child: Text(i18n(context).register),
          ),
          onPressed: (_isClick && _isAgree) ? _userRegist : null,
        ),
        Gaps.vGap15,
        Center(
          child: TextButton(
            child: Text(i18n(context).forgetPassword),
            onPressed: () {
              NavigatorUtils.push(context, LoginRouter.forgetPassword);
            },
          ),
        ),
        // ...buildThird(),
        Gaps.vGap35,
        _buildClause(),
      ],
    );
  }

  List<Widget> buildThird() {
    return [
      Gaps.vGap35,
      Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(child: Divider(indent: 0.0)),
          Gaps.hGap8,
          Text(
            i18n(context).thirdRegister,
          ),
          Gaps.hGap8,
          Expanded(child: Divider(indent: 0.0)),
        ],
      ),
      Gaps.vGap30,
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RawMaterialButton(
            child: Icon(
              Iconfont.weixinhaoyou,
              color: Colors.white,
              size: Dimens.gapDp25,
            ),
            shape: CircleBorder(),
            padding: EdgeInsets.all(Dimens.gapDp13),
            elevation: 0.0,
            highlightElevation: 0.0,
            fillColor: Color(0xFF70CB5B),
            onPressed: () {},
          ),
          RawMaterialButton(
            child: Icon(
              Iconfont.qq,
              color: Colors.white,
              size: Dimens.gapDp25,
            ),
            shape: CircleBorder(),
            padding: EdgeInsets.all(Dimens.gapDp13),
            elevation: 0.0,
            highlightElevation: 0.0,
            fillColor: Color(0xFF6CB4F3),
            onPressed: () {},
          ),
          RawMaterialButton(
            child: Icon(
              Iconfont.xinlang1,
              color: Colors.white,
              size: Dimens.gapDp25,
            ),
            shape: CircleBorder(),
            padding: EdgeInsets.all(Dimens.gapDp13),
            elevation: 0.0,
            highlightElevation: 0.0,
            fillColor: Color(0xFFDC6C55),
            onPressed: () {},
          ),
        ],
      ),
    ];
  }

  Widget _buildClause() {
    return Center(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RawMaterialButton(
                onPressed: _agreeAction,
                child: Icon(
                  Icons.done,
                  size: Dimens.gapDp11,
                  color: Colors.white,
                ),
                shape: CircleBorder(),
                elevation: 0.0,
                fillColor: _isAgree
                    ? ThemeUtil.primaryColor(context)
                    : ThemeUtil.disabledColor(context),
                constraints: BoxConstraints(
                  minHeight: Dimens.gapDp16,
                  minWidth: Dimens.gapDp16,
                ),
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              Gaps.hGap8,
              GestureDetector(
                child: Text(
                  i18n(context).agreeTerms,
                  style:
                      TextStyles.bodySmall!.copyWith(fontSize: Dimens.fontSp13),
                ),
                onTap: _agreeAction,
              ),
            ],
          ),
          Gaps.vGap5,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
                child: Text(
                  "《${i18n(context).serviceAgreement}》",
                  style: TextStyles.bodySmall!.copyWith(
                    fontSize: Dimens.fontSp12,
                    color: Color(0xFF52BBF4),
                  ),
                ),
                onTap: () {
                  var isDark = ThemeUtil.isDark(context);
                  NavigatorUtils.goWebViewPage(
                    context,
                    i18n(context).serviceAgreement,
                    "${Configs.WEB_SERVICE_AGREEMENT}${isDark ? '_dark' : ''}/",
                  );
                },
              ),
              Text(
                i18n(context).and,
                style:
                    TextStyles.bodySmall!.copyWith(fontSize: Dimens.fontSp13),
              ),
              InkWell(
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
                child: Text(
                  "《${i18n(context).privacyPolicy}》",
                  style: TextStyles.bodySmall!.copyWith(
                    fontSize: Dimens.fontSp12,
                    color: Color(0xFF52BBF4),
                  ),
                ),
                onTap: () {
                  var isDark = ThemeUtil.isDark(context);
                  NavigatorUtils.goWebViewPage(
                    context,
                    i18n(context).privacyPolicy,
                    "${Configs.WEB_PRIVACY_POLICY}${isDark ? '_dark' : ''}/",
                  );
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _agreeAction() {
    setState(() {
      _isAgree = !_isAgree;
    });
  }

  /// 用户注册
  void _userRegist() {
    String username = _usernameController.text;
    String password = _passwordController.text;
    FocusManager.instance.primaryFocus?.unfocus();
    UserApi.userRegist(username, password).then((val) {
      NavigatorUtils.goBack(context);
    });
  }
}
